import ApiPageList from "@/api/ApiV1WxAccountPageList_post"; // TAV
import { ReloadOutlined } from "@ant-design/icons";
import { Button, Dropdown, Typography } from "antd";
import { useCallback, useEffect, useMemo, useState } from "react";
import { Paging } from "../../../utils/Paging";
import { FlexHeader, FlexRoot, ListEmpty } from "../../_BaseView/FlexRoot";
import { List } from "../../_BaseView/List";
import { AccountItem } from "./AccountItem";
import { useImmer } from "use-immer";
import { AccountEditModal } from "@/views/AccountEditView";
export interface IRespItem extends ApiPageList.RespData { }
export interface IUIItem extends ApiPageList.RespData { }

export default function AccountManagement() {
  const [refresh_flag, set_refresh_flag] = useState(0);
  const [_list, set_list] = useState<IUIItem[]>([]);
  const [loading, set_loading] = useState(false);
  const [total, set_total] = useState(0)
  const [editing_item, set_editing_item] = useImmer<{ open?: boolean, data?: IUIItem }>({});

  const loader = useMemo(() => new Paging<IUIItem, ApiPageList.BodyParams>(50, {}, async (p) => {
    const body: ApiPageList.BodyParams = {
      pageNo: p.page, pageSize: p.page_size
    }
    const r = await ApiPageList.call(body);
    const raws: IRespItem[] = (r as any).data ?? []
    const total = (r as any).totalCount ?? raws.length ?? 0
    set_total(total)
    p.set_total(total)
    return raws
  }).on_loading(r => set_loading(r.loading)), [])

  useEffect(() => {
    loader.load(true).then(r => set_list(r))
  }, [refresh_flag])

  const render_item = useCallback((item: IUIItem) => {
    return (
      <Dropdown
        trigger={['contextMenu']}
        menu={{ items: [{ key: '_', label: '修改信息', onClick: () => set_editing_item({ open: true, data: item }) }] }}>
        <AccountItem item={item} key={item.account} />
      </Dropdown>
    )
  }, [])
  const load_more = () => {
    if (loader.loading || loader.finish) return;
    loader.load().then(r => set_list(r))
  };
  return (
    <FlexRoot vertical>
      <FlexHeader>
        <Typography.Text type='secondary'>共有{total}个账号</Typography.Text>
        <Button type="text" size="small" onClick={() => set_refresh_flag(v => ++v)}>
          <ReloadOutlined />
        </Button>
      </FlexHeader>
      <List
        virtual={_list.length > 100}
        data={_list}
        itemHeight={71}
        itemKey={i => `${i.account}_${i.id}`}
        on_reach_end={load_more}
        others={<ListEmpty show={!total && !loading} description='' />}>
        {render_item}
      </List>

      <AccountEditModal
        open={editing_item.open}
        onCancel={() => set_editing_item(o => { o.open = false })}
        afterClose={() => set_editing_item(o => { o.data = void 0 })}
        data={editing_item.data}
        on_success={(edited) => {
          set_editing_item(o => { o.open = false })
          set_list(o => {
            const ret = [...o];
            const index = ret.findIndex(a => a.account === edited.account)
            if (index >= 0) ret[index] = edited;
            return ret;
          })
        }} />
    </FlexRoot>
  )
}